<script setup>
import { ref, computed, onMounted } from "vue";
import { IconLeft, IconRight } from "@arco-design/web-vue/es/icon";
import { QuestionControllerService } from "../../../generatedQue/services/QuestionControllerService";
onMounted(async () => {
  console.log("mounted");
  console.log(currentDate.value.getFullYear());
  console.log(currentDate.value.getMonth() + 1);
  await getStudyData();
});
const getStudyData = async () => {
  const res =
    await QuestionControllerService.getQuestionSubmitCountByUserUsingPost("", {
      month: currentDate.value.getMonth() + 1,
      year: currentDate.value.getFullYear(),
    });
  console.log(res);
  studyData.value = res.data;
  console.log(studyData.value);
};
// 模拟数据
const studyData = ref({
  "2024-5-20": 3,
  "2024-5-15": 5,
  "2024-5-25": 8,
});
// 新增工具函数，格式化日期为 YYYY-MM-DD 格式
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0"); // 补零
  const day = date.getDate().toString().padStart(2, "0");
  return `${year}-${month}-${day}`;
};
const currentDate = ref(new Date());
const detailVisible = ref(false);
const selectedDateObj = ref(null);

const weekDays = ["日", "一", "二", "三", "四", "五", "六"];

// 生成当月日历
const calendarDates = computed(() => {
  const year = currentDate.value.getFullYear();
  const month = currentDate.value.getMonth();
  const firstDay = new Date(year, month, 1);
  const lastDay = new Date(year, month + 1, 0);
  const dates = [];

  // 填充上月日期
  for (let i = firstDay.getDay(); i > 0; i--) {
    dates.push(new Date(year, month, -i + 1));
  }

  // 填充本月日期
  for (let i = 1; i <= lastDay.getDate(); i++) {
    dates.push(new Date(year, month, i));
  }

  // 填充下月日期
  const nextMonthDays = 42 - dates.length;
  for (let i = 1; i <= nextMonthDays; i++) {
    dates.push(new Date(year, month + 1, i));
  }

  return dates;
});

const currentMonth = computed(() => {
  return currentDate.value.toLocaleString("zh-CN", {
    year: "numeric",
    month: "long",
  });
});

// 修改后的：获取解题数量（加入空值判断）
const getSolvedCount = (date) => {
  if (!date) return 0;
  const key = formatDate(date);
  return studyData.value[key] || 0;
};

// 新增 computed，用于格式化模态框标题的显示日期
const selectedDate = computed(() => {
  return selectedDateObj.value
    ? selectedDateObj.value.toLocaleDateString()
    : "";
});

// 样式相关方法
const getCellStatus = (date) => {
  if (date.getMonth() !== currentDate.value.getMonth()) {
    return "other-month";
  }
  return getSolvedCount(date) > 0 ? "has-data" : "no-data";
};

const isToday = (date) => {
  const today = new Date();
  return date.toDateString() === today.toDateString();
};

const getDotColor = (n) => {
  const colors = ["#7be4ff", "#4dabf7", "#1c7ed6", "#1864ab"];
  return colors[Math.min(n - 1, 3)];
};

// 操作
const prevMonth = async () => {
  currentDate.value = new Date(
    currentDate.value.getFullYear(),
    currentDate.value.getMonth() - 1
  );
  await getStudyData();
};

const nextMonth = async () => {
  currentDate.value = new Date(
    currentDate.value.getFullYear(),
    currentDate.value.getMonth() + 1
  );
  await getStudyData();
};

const showDateDetail = (date) => {
  selectedDateObj.value = date;
  detailVisible.value = true;
};
</script>

<template>
  <div class="study-calendar-container">
    <!-- 头部 -->
    <div class="calendar-header">
      <a-button @click="prevMonth" type="text">
        <icon-left />
      </a-button>
      <h2>{{ currentMonth }}</h2>
      <a-button @click="nextMonth" type="text">
        <icon-right />
      </a-button>
    </div>

    <!-- 星期标题 -->
    <div class="calendar-weekdays">
      <div v-for="day in weekDays" :key="day" class="weekday">{{ day }}</div>
    </div>

    <!-- 日期格子 -->
    <div class="calendar-grid">
      <div
        v-for="(date, index) in calendarDates"
        :key="index"
        class="calendar-cell"
        :class="[getCellStatus(date), { today: isToday(date) }]"
        @click="showDateDetail(date)"
      >
        <div class="date-number">{{ date.getDate() }}</div>
        <div class="progress-dots">
          <div
            v-for="n in getSolvedCount(date)"
            :key="n"
            class="dot"
            :style="{ backgroundColor: getDotColor(n) }"
          ></div>
        </div>
      </div>
    </div>

    <!-- 日期详情弹窗 -->
    <a-modal
      v-model:visible="detailVisible"
      :title="selectedDate"
      :footer="false"
      :getPopupContainer="() => document.body"
    >
      <div class="date-detail">
        <p v-if="getSolvedCount(selectedDateObj) > 0">
          今日刷题数：{{ getSolvedCount(selectedDateObj) }} 题
        </p>
        <p v-else>今日暂无刷题记录</p>
      </div>
    </a-modal>
  </div>
</template>

<style scoped>
.study-calendar-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.calendar-header {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20px;
  margin-bottom: 20px;
}

.calendar-weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 2px;
  margin-bottom: 8px;
}

.weekday {
  text-align: center;
  padding: 8px;
  color: #666;
  font-weight: 500;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 2px;
}

.calendar-cell {
  aspect-ratio: 1;
  background: white;
  border-radius: 4px;
  padding: 8px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
}

.calendar-cell:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.other-month {
  background: #f8f9fa;
  color: #999;
}

.today {
  outline: 2px solid var(--color-primary-light-3);
}

.has-data {
  background: linear-gradient(
    135deg,
    rgba(77, 171, 247, 0.1) 0%,
    rgba(28, 126, 214, 0.15) 100%
  );
}

.date-number {
  font-size: 14px;
  align-self: flex-start;
}

.progress-dots {
  display: flex;
  gap: 2px;
  flex-wrap: wrap;
  justify-content: center;
}

.dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
}

.date-detail {
  text-align: center;
  padding: 20px;
}
</style>
